import router from "@/routers";
import store from "./store";

router.beforeEach(async (to, from, next) => {
  document.title = "商城-" + to.meta.title;
  let { token, nickname } = store.state.user;
  //白名单数组[未登录不能访问的路由]
  let whiteList = [
    "/cartsuccess",
    "/trade",
    "/pay",
    "/paysuccess",
    "/center",
    "/center/myorder",
    "/center/teamorder",
  ];
  if (token) {
    if (to.path == "/login" || to.path == "/register") {
      next({ path: "/home" });
    } else {
      //有token值 且跳转的页面不是登录注册页面时
      if (nickname) {
        //有用户信息
        next();
      } else {
        //无用户信息
        //刷新的时候没有用户信息发请求获取到用户信息成功了在放行
        try {
          await store.dispatch("getUserInfo");
          next();
        } catch (e) {
          await store.dispatch("userLogout");
          next({ path: "/login" });
        }
      }
    }
    next();
  } else {
    if (whiteList.includes(to.path)) {
      next({ path: "/login", query: { redirect: to.path } });
    } else {
      next();
    }
  }
});
